<!--
  -    Copyright (c) 2018-2025, lengleng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: lengleng (wangiegie@gmail.com)
  -->
<template>
  <div class="execution">
    <basic-container>
      <el-tabs
        v-model="activeName"
        @tab-click="handleClick"
      >
        <el-tab-pane
          label="商用车"
          name="0"
        ></el-tab-pane>
        <el-tab-pane
          label="非商用车"
          name="1"
        ></el-tab-pane>
      </el-tabs>
      <avue-crud
        ref="crud"
        :page.sync="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        :search.sync="searchForm"
        @on-load="getList"
        @search-change="searchChange"
        @search-reset="searchReset"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
      >
        <template slot="nameSearch">
          <el-autocomplete
            style="width:100%;"
            class="inline-input"
            v-model="searchForm.name"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
          ></el-autocomplete><!-- 注释掉了 @select="handleSelect" --> 
        </template>
        <template
          slot="carTypeSearch"
        >
          <el-select
            v-model="searchForm.carTypeName"
            @change="carTypeChange"
          >
            <el-option
              v-for="(item,index) in carTypeList"
              :label="item.name"
              :key="index"
              :value="item.id"
            ></el-option>
          </el-select>
        </template>
        <template
          slot="carBrandSearch"
        
        >
          <el-select
            v-model="searchForm.carBrandName"
            @change="carBrandChange"
          >
            <el-option
              v-for="(item,index) in carBrandList"
              :label="item.name"
              :key="index"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </template>
        <template
         
          slot="enterInTimeSearch"
        >
          <el-date-picker
            v-model="date.in"
            type="datetimerange"
            range-separator="~"
            start-placeholder="入场开始时间"
            end-placeholder="入场结束时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </template>
        <template
         
          slot="comeOutTimeSearch"
        >
          <el-date-picker
            v-model="date.out"
            type="datetimerange"
            range-separator="~"
            start-placeholder="出场开始时间"
            end-placeholder="出场结束时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </template>
        <template
          slot="searchMenu"
          slot-scope="{row,size}"
        >
          <el-button
            :size="size"
            icon="el-icon-upload2"
            @click="searchexport(row)"
          >导出</el-button>
        </template>
        <template
          slot="menu"
          slot-scope="scope"
        >
          <el-button
            size="small"
            type="text"
            @click="Edit(scope.row)"
            v-if="tabActiveName!=4"
          >编辑</el-button>
          <el-button
            size="small"
            type="text"
            @click="Detailid(scope.row)"
          >查看</el-button>
        </template>

        <template
          slot="menuLeft"
        >
          <el-tabs
            v-model="tabActiveName"
            @tab-click="tabhandleClick"
            class="tab-border-nogray"
          >
            <el-tab-pane
              v-for="item in tabOption"
              :key="item.value"
              :label="item.label"
              :name="item.value"
            ></el-tab-pane>
          </el-tabs>
        </template>
      </avue-crud>
      <detail-and-edit
        ref="DetailAndEdit"
        @refresh="updateList"
        @handleUpdate="handleUpdate"
      ></detail-and-edit>
      <edit
        ref="Edit"
        @refresh="updateList"
      ></edit>
    </basic-container>
  </div>
</template>

<script>
import { fetchList, getObj, addObj, putObj, delObj, exportExcel, CrCarType, carCompany } from '@/api/crcar'
import { tableOption } from '@/const/crud/crcar'
import { mapGetters } from 'vuex'
import DetailAndEdit from './DetailAndEdit'
import edit from './Edit'
export default {
  name: 'crcar',
  components: {
    'detail-and-edit': DetailAndEdit,
    edit
  },
  data () {
    return {
      date: {
        in: [],
        out: []
      },
      searchForm: {
        name: '',
        isBusinessCar: 0,
        carStatus: 0,
        type: 1,
        carType: '',
        carTypeName: '',
        carBrand: '',
        carBrandName: ''
      },
      carTypeList: [],
      carBrandList: [],
      tableData: [],
      activeName: 0,
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,
      tabActiveName: '1',
      tabOption: [{
        label: '入场车辆',
        value: '1'
      }, {
        label: '出场车辆',
        value: '4'
      }],
      restaurants: []
    }
  },
  computed: {
    ...mapGetters(['permissions']),
    permissionList () {
      return {
        addBtn: this.vaildData(this.permissions.car_crcar_add, false),
        delBtn: this.vaildData(this.permissions.car_crcar_del, false),
        editBtn: this.vaildData(this.permissions.car_crcar_edit, false)
      };
    }
  },
  mounted () {
    CrCarType(1).then(res => {
      this.carTypeList = res.data.data
    })
    CrCarType(3).then(res => {
      this.carBrandList = res.data.data
    })
    carCompany().then(({ data }) => {
      for (let key in data.data) {
        this.restaurants.push({ value: key, label: data.data[key] })
      }
    })
  },
  methods: {
    querySearch (queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      var newresults = []
      results.forEach(item => {
        newresults.push({ value: item.label })
      })
      // 调用 callback 返回建议列表的数据
      // cb(results);
      cb(newresults)
    },
    createFilter (queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) != -1);
      };
    },
    carTypeChange () {
      this.carTypeList.forEach(item => {
        if (item.id == this.searchForm.carTypeName) {
          this.searchForm.carType = item.name
        }
      })
    },
    carBrandChange () {
      this.carBrandList.forEach(item => {
        if (item.id == this.searchForm.carBrandName) {
          this.searchForm.carBrand = item.name
        }
      })
    },
    // 车儿编辑
    Edit (item) {
      this.$refs.Edit.init(item, this.activeName)
    },
    // 导出功能
    searchexport (row, params) {
      this.tableLoading = true
      this.searchForm.isBusinessCar = this.activeName
      this.searchForm.carStatus = this.tabActiveName
      if (this.tabActiveName === '1') {
        this.searchForm.type = 3
      } else {
        this.searchForm.type = 4
      }
      // 测试提出导出未筛选前的数据，去掉this.searchForm
      exportExcel(Object.assign({}, params, this.searchForm)).then(response => {
        if (!response) {
          return
        }
        let link = document.createElement('a')
        link.href = window.URL.createObjectURL(new Blob([response.data]))
        link.target = '_blank'
        let filename = response.headers['content-disposition']
        link.download = decodeURI(filename)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    searchReset () {
      this.date = {
        out: [],
        in: []
      }
      this.searchForm.carType = ''
      this.searchForm.carTypeName = ''
      this.searchForm.carBrand = ''
      this.searchForm.carBrandName = ''
    },
    // 进场车辆和出场车辆切换
    tabhandleClick () {
      this.getList(this.page)
      if (this.tabActiveName !== '4') {
        this.date.out = []
        this.tableOption.column.splice(8, 1)
      } else {
        this.tableOption.column.splice(8, 1, {
          "type": "datetime",
          "search": true,
          "label": "出场时间",
          hide: false,
          "prop": "comeOutTime",
          format: "yyyy-MM-dd HH:mm:ss",
          valueFormat: "yyyy-MM-dd HH:mm:ss",
          searchslot: true,
          searchSpan: 9
        })
      }
    },
    // tabs 选择tabs切换动作
    handleClick () {
      this.getList(this.page)
      if (this.activeName === '1') {
        this.tableOption.column[1].hide = false
        this.tableOption.column[2].hide = true
        this.tableOption.column[1].search = true
        this.tableOption.column[2].search = false
      } else {
        this.tableOption.column[1].hide = true
        this.tableOption.column[2].hide = false
        this.tableOption.column[1].search = false
        this.tableOption.column[2].search = true
      }
    },
    // 查看对应数据的详情
    Detailid (row) {
      this.$refs.DetailAndEdit.init(row, this.activeName, this.tabActiveName)
    },
    updateList () {
      this.getList(this.page)
    },
    getList (page, params) {
      this.tableLoading = true
      this.searchForm.isBusinessCar = this.activeName
      this.searchForm.carStatus = this.tabActiveName === '0' ? '' : this.tabActiveName
      if (this.date.in && this.date.in.length == 2) {
        this.searchForm.startInTime = this.date.in[0]
        this.searchForm.endInTime = this.date.in[1]
      }
      if (this.date.out && this.date.out.length == 2) {
        this.searchForm.startOutTime = this.date.out[0]
        this.searchForm.endOutTime = this.date.out[1]
      }
      fetchList(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchForm)).then(response => {
        this.tableData = response.data.data.records
        this.page.total = response.data.data.total
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    rowDel: function (row, index) {
      this.$confirm('是否确认删除此条数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delObj(row.id)
      }).then(data => {
        this.$message.success('删除成功')
        this.getList(this.page)
      })
    },
    handleUpdate: function (row, index, done, loading) {
      putObj(row).then(data => {
        this.$message.success('修改成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        if (loading) {
          loading();
        }
      });
    },
    handleSave: function (row, done, loading) {
      addObj(row).then(data => {
        this.$message.success('添加成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        if (loading) {
          loading();
        }
      });
    },
    sizeChange (pageSize) {
      this.page.pageSize = pageSize
      this.getList(this.page)
    },
    currentChange (current) {
      this.page.currentPage = current
      this.getList(this.page)
    },
    searchChange (form, done) {
      // this.searchForm = form
      this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },
    refreshChange () {
      this.getList(this.page)
    }
  }
}
</script>
